#include <socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

/* Creates a new socket and returns the socket descriptor */
int socket_setup(int portno){

	int 	sockfd;
	char 	buffer[256];
	struct 	sockaddr_in serv_addr;
	
	/* create TCP socket */
	sockfd = socket(AF_INET, SOCK_STREAM, 0); // why 0?
	
	/* check that our socket opens correctly and is valid */
	if(sockfd < 0){
		perror("ERROR could not open socket");
		exit(1);
	}

	/* create server address */
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(portno);
	
	/* bind the server address to the socket and check for validity */
	if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
		perror("ERROR could not bind address to socket");
		exit(1);
	}
	
	return 0;
}

/*
  Listens for a new connection,
  once there is a new connection
  the file descriptor of the new open connection is returned.
*/
int socket_get_new_connection(int sockfd){
	
	int 	clilen, newsockfd;
	struct 	sockaddr_in cli_addr;
	
	/* listen on the socket; accept up to (int) connections */
	listen(sockfd, 101);
	clilen = sizeof(cli_addr);
	
	/* accept connection, return new socket for communication */
	newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); 
	if(newsockfd < 0){
		perror("ERROR connection refused");
		exit(1);
	}
	
	return 0;
}

/*
  Reads a 'line' from the given connection.
  A 'line' means a sequence of characters ending with a CRLF pair.
  The string being returned must include the CRLF pair.
*/
char* socket_get_line(int fd){

	int 	n;
	char 	buffer[256];
	
	n = read(fd, buffer, 255);

	if(n < 0){
		perror("ERROR reading from socket");
		exit(1);
	}
	
	// printf("Message: %s\n", buffer);		// for checking?
	
	return 0;
}


/* Writes the given string to the given connection descriptor */
void socket_write(int fd, char* string){
	
	int n;
	
	n = write(fd, "Message received", 18); 		// last argument value?
	
	if(n < 0){
		perror("ERROR writing to socket");
		exit(1);
	}
}

/* Closes the given connection descriptor */
void close_connection(int fd){
	
}

/* Closes the given socket */
void close_socket(int fd){
	close(fd);
}

